const { parentPort, workerData } = require('worker_threads')
const { editUserTaskStatus, initializeDatabase } = require('./database')
const qs = require('qs')
const md5 = require('md5')

// 从workerData中获取数据
const { dbPath } = workerData
console.log(`BatchTaskWorker: 初始化数据库，路径为 ${dbPath}`)
let db = null

try {
  db = initializeDatabase(dbPath)
  console.log('BatchTaskWorker: 数据库初始化成功')
} catch (error) {
  console.error('BatchTaskWorker: 数据库初始化失败', error)
  // 向主线程发送初始化失败的消息
  parentPort.postMessage({
    success: false,
    error: `数据库初始化失败: ${error.message}`
  })
}

// 🚀 每批发送 10 个请求
const BATCH_SIZE = 2
async function fetchInBatches(input) {
  const results = []

  for (let i = 0; i < input.tasks.length; i += BATCH_SIZE) {
    const tasks = input.tasks.slice(i, i + BATCH_SIZE)
    console.log(`开始处理任务 ${input.uid}-${input.cookie}-${JSON.stringify(tasks)}`)
    const batchPromises = tasks.map((t) => getShopNameByNet(t, input.uid, input.cookie))

    try {
      const batchResults = await Promise.all(batchPromises)
      results.push(...batchResults)
      console.log(`批次 ${i / BATCH_SIZE + 1} 结果！,${JSON.stringify(batchResults)}`)
      // 写入数据库中
      for (let i = 0; i < tasks.length; i++) {
        // id, status,result, resp
        editUserTaskStatus(db, tasks[i].id, 1, JSON.stringify(batchResults[i]))
          .then((id) => {
            console.log('editUserTaskStatus update success:', id)
          })
          .catch((err) => {
            console.log('editUserTaskStatus err:', err)
          })
      }
      console.log(`批次 ${i / BATCH_SIZE + 1} 完成！`)
    } catch (err) {
      console.error(`${i / BATCH_SIZE + 1} 失败：`, err)
    }
  }

  return results
}

// worker.js
// 监听主线程消息
parentPort.onmessage = async function (e) {
  const { id, value } = e.data
  console.log(`[SubmitWorker ${id}] 接收到主线程消息, 数据:`, value)

  try {
    // 调用计算函数，传递workerId和输入数据
    console.log(`[SubmitWorker ${id}] 开始执行heavyCalculation`)
    const result = await heavyCalculation(id, value)
    console.log(`[SubmitWorker ${id}] heavyCalculation执行完成, 结果长度:`, result?.length || 0)
    console.log(`${id}  成功：`, result)

    // 返回结果和ID以便主线程识别
    console.log(`[SubmitWorker ${id}] 准备发送结果回主线程`)
    parentPort.postMessage({ id, result, success: true })
    console.log(`[SubmitWorker ${id}] 结果已发送回主线程`)
  } catch (error) {
    console.error(`[SubmitWorker ${id}] 计算失败`, error)
    console.log(`[SubmitWorker ${id}] 准备发送错误信息回主线程`)
    parentPort.postMessage({ id, error: error.message, success: false })
    console.log(`[SubmitWorker ${id}] 错误信息已发送回主线程`)
  }
}

async function heavyCalculation(workerId, input) {
  let result = await fetchInBatches(input)

  return result
}

const getShopNameByNet = (result, uid, cookie) => {
  return new Promise((resolve) => {
    resolve({
      success: true,
      data: {
        shopName: '测试店铺',
        uid: uid,
        cookie: cookie,
        task: result.task,
        result: result.result
      },
      message: '获取店铺名称成功'
    })
  })
  // return new Promise((resolve, reject) => {
  //   let url = 'https://h5api.m.taobao.com/h5/mtop.alibaba.shop.shopinfo.info.get/1.0/'
  //   // 获取毫秒数
  //   let time = new Date().getTime()
  //   let reqParams = '{"isFast":false}'
  //   let params1 = {
  //     jsv: '2.6.1',
  //     appKey: '12574478',
  //     t: time,
  //     sign: '',
  //     api: 'mtop.alibaba.shop.shopinfo.info.get',
  //     v: '1.0',
  //     ttid: '11320@taobao_WEB_9.9.99',
  //     dataType: 'originaljsonp',
  //     type: 'originaljsonp',
  //     callback: 'mtopjsonp19',
  //     data: reqParams
  //   }
  //   let token = ''
  //   cookie.split(';').forEach((item) => {
  //     let arr = item.split('=')
  //     if (arr[0].trim() == '_m_h5_tk') {
  //       token = arr[1].split('_')[0]
  //     }
  //   })
  //   let sign = `${token}&${time}&12574478&${reqParams}`
  //   params1.sign = md5(sign)
  //   // 直接把params拼接到url上
  //   url += '?' + qs.stringify(params1)
  //   console.log('url:', url)
  //   // 使用fetch发送请求
  //   var myHeaders = new Headers()
  //   myHeaders.append('accept', '*/*')
  //   myHeaders.append('accept-language', 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6')
  //   myHeaders.append('cache-control', 'no-cache')
  //   myHeaders.append('pragma', 'no-cache')
  //   myHeaders.append('referer', 'https://qn.taobao.com/home.htm/shop-manage/shop-center')
  //   myHeaders.append(
  //     'sec-ch-ua',
  //     '"Chromium";v="134", "Not:A-Brand";v="24", "Microsoft Edge";v="134"'
  //   )
  //   myHeaders.append('sec-ch-ua-mobile', '?0')
  //   myHeaders.append('sec-ch-ua-platform', '"Windows"')
  //   myHeaders.append('sec-fetch-dest', 'script')
  //   myHeaders.append('sec-fetch-mode', 'no-cors')
  //   myHeaders.append('sec-fetch-site', 'same-site')
  //   myHeaders.append(
  //     'user-agent',
  //     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0'
  //   )
  //   myHeaders.append('Cookie', cookie)

  //   console.log('Cookie:', cookie)
  //   var requestOptions = {
  //     method: 'GET',
  //     headers: myHeaders,
  //     redirect: 'follow'
  //   }

  //   fetch(url, requestOptions)
  //     .then((response) => {
  //       if (!response.ok) {
  //         throw new Error(`HTTP error! Status: ${response.status}`)
  //       }
  //       return response.text()
  //     })
  //     .then((data) => {
  //       // 尝试解析JSONP响应
  //       try {
  //         // 移除JSONP包装
  //         const jsonpData = data.replace(/^mtopjsonp19\((.*)\)$/, '$1')
  //         const parsedData = JSON.parse(jsonpData)
  //         resolve({
  //           success: true,
  //           data: parsedData,
  //           message: '获取店铺名称成功'
  //         })
  //       } catch (error) {
  //         resolve({
  //           success: true,
  //           data: data,
  //           message: '获取店铺名称成功，但解析失败',
  //           parseError: error.message
  //         })
  //       }
  //     })
  //     .catch((error) => {
  //       console.error('Error:', error)
  //       reject({
  //         success: false,
  //         data: null,
  //         message: '获取店铺名称失败',
  //         error: error.message
  //       })
  //     })
  // })
}
